package com.lemo.smart.helper;

import com.lemo.smart.annotation.Controller;
import com.lemo.smart.annotation.Service;
import com.lemo.smart.util.ClassUtil;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

/**
 * 类操作助手类
 * Created by 罗选通 on 2017/12/22.
 */
public class ClassHelper {
  /**
   * 定义类集合，用于存放所加载的类
   */
  private static final Set<Class<?>> CLASS_SET;

  static {
    String basePackage = ConfigHelper.getBasePackage();
    CLASS_SET = ClassUtil.getClassSet(basePackage);
  }

  /**
   * 获取应用报名下的所有类
   */
  public static Set<Class<?>> getClassSet() {
    return CLASS_SET;
  }

  /**
   * 获取所有Service类
   */
  public static Set<Class<?>> getServiceClassSet() {
    Set<Class<?>> classeSet = new HashSet<Class<?>>();
    for (Class<?> cls : CLASS_SET) {
      if (cls.isAnnotationPresent(Service.class)) {
        classeSet.add(cls);
      }
    }
    return classeSet;
  }

  /**
   * 获取所有Controller类
   */
  public static Set<Class<?>> getControllerClassSet() {
    Set<Class<?>> classeSet = new HashSet<Class<?>>();
    for (Class<?> cls : CLASS_SET) {
      if (cls.isAnnotationPresent(Controller.class)) {
        classeSet.add(cls);
      }
    }
    return classeSet;
  }

  /**
   * 获取所有bean(Service,Controller)
   */
  public static Set<Class<?>> getBeanClassSet() {
    Set<Class<?>> classeSet = new HashSet<Class<?>>();
    classeSet.addAll(getServiceClassSet());
    classeSet.addAll(getControllerClassSet());
    return classeSet;
  }


  /**
   * 获取项目包名下父类或接口的实现类
   */
  public static Set<Class<?>> getClassSetBySuper(Class<?> superClass) {
    Set<Class<?>> classes = new HashSet<>();
    for (Class<?> cls : CLASS_SET) {
      if (superClass.isAssignableFrom(cls) && !superClass.equals(cls)) {
        classes.add(cls);
      }
    }
    return classes;
  }

  /**
   * 获取所有带有某注解的类
   * @param annotationClass
   * @return
   */
  public static Set<Class<?>> getClassSetByAnnotation(Class<? extends Annotation> annotationClass) {
    Set<Class<?>> classes = new HashSet<>();
    for (Class<?> cls : CLASS_SET) {
      if (cls.isAnnotationPresent(annotationClass)) {
        classes.add(cls);
      }
    }
    return classes;
  }




}
